﻿$(document).ready(function () {
    
    function hasClass(element, cls) {
        return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
    }
    $(function HubGame() {
        var con = $.hubConnection();
        var hub = con.createHubProxy('Game');
        var myid = document.getElementById("myId").value;
        var signalRConnectionId = document.getElementById("signalRConnectionId").value;
        if (myid != "") {
            con.start(function () {
                hub.invoke('Hello', myid, -1);
            });
        }

        hub.on('challenged', function (userid) {
            var user = document.querySelectorAll('[data-userid~="' + userid + '"]');
            var label = user.getElementsByClassName("label fg-black");
            label.className = "label fg-red";
        });

        hub.on('hello', function (users ,games, connectionId) {
            document.getElementById("signalRConnectionId").value=connectionId;
            var currentGames = document.getElementById('currentGames');
            while (currentGames.firstChild) {
                currentGames.removeChild(currentGames.firstChild);
            }
            for (index = 0; index < games.length; ++index) {
                $("#currentGames").append(games[index]);
            }
            var userse = document.getElementById('users');
            while (userse.firstChild) {
                userse.removeChild(userse.firstChild);
            }
            for (index = 0; index < users.length; ++index) {
                $("#users").append(users[index]);
            }
        });

        hub.on('game', function (gameId, stringGame) {
            if(stringGame!="youagain")
                $("#currentGames").append(stringGame);
        });
      

        hub.on('attacked', function (x, y, victory) {
           //changetext
        });

        hub.on('message', function (message, game) {
           //changetext
        });
        
      

        $("#newGame").click(function () {
            var myid = document.getElementById("myId").value;
            hub.invoke('NewGame', myid);
        });

        $("#botGame").click(function () {
            var myid = document.getElementById("myId").value;
            hub.invoke('NewBotGame', myid);
        });

        $(document).on("click", "#challenge", function () {
            var label = this.getElementsByClassName("label fg-black");
            if (label != null) {
                var myid = document.getElementById("myId").value;
                var userid = $(this).data("userid");
                hub.invoke('Challenge', myid, userid);
            }
            else {
                var myid = document.getElementById("myId").value;
                var userid = $(this).data("userid");
                hub.invoke('AcceptChallenge', myid, userid);
            }
        });
    });
})